package com.gt.quality.utils;

import com.gt.quality.base.BusinessSelfException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Locale;

/**
 * 万里悲秋常作客,百年多病独登台
 *
 * @author : makeJava
 */
@Component
@Slf4j
@SuppressWarnings("all")
public class FileCopyToLocal {

    @Value("${sys.conf.file.path}")
    private String filePath;

    @Value("${window.dev.file.path}")
    private String windowPath;

    public String copyToLocalCallBackPath(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String env = System.getProperty("os.name").toLowerCase(Locale.ROOT);
        if (env.contains("win")) {
            filePath = windowPath;
        }
        String sysFilePath = this.getPathDefaultProxy(filePath) + originalFilename;
        File realFile = new File(sysFilePath);
        if (!realFile.exists()) {
            boolean result = realFile.mkdirs();
            log.info("文件创建--->{}:{}", filePath, result);
        }
        // 保存到上传到服务器
        try {
            file.transferTo(realFile);
        } catch (IOException e) {
            log.error("文件上传失败: {}", e.getMessage(), e);
            throw new BusinessSelfException(e.getMessage());
        }
        return sysFilePath;
    }

    public File copyToLocalCallBackFile(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String env = System.getProperty("os.name").toLowerCase(Locale.ROOT);
        if (env.contains("win")) {
            filePath = windowPath;
        }
        String sysFilePath = this.getPathDefaultProxy(filePath) + originalFilename;
        File realFile = new File(sysFilePath);
        if (!realFile.exists()) {
            boolean result = realFile.mkdirs();
            log.info("文件创建--->{}:{}", filePath, result);
        }
        // 保存到上传到服务器
        try {
            file.transferTo(realFile);
        } catch (IOException e) {
            log.error("文件上传失败: {}", e.getMessage(), e);
            throw new BusinessSelfException(e.getMessage());
        }
        return realFile;
    }

    /**
     * 获取文件系统的基建路径
     *
     * @param basePath basePath
     * @return String
     */
    public String getPathDefaultProxy(String basePath) {
        LocalDateTime now = LocalDateTime.now();
        int year = now.getYear();
        int month = now.getMonth().getValue();
        int dayOfMonth = now.getDayOfMonth();
        return basePath +
               File.separator +
               year +
               File.separator +
               month +
               File.separator +
               dayOfMonth + File.separator;
    }
}
